|
1 | 1 | from langchain.output_parsers import ResponseSchema, StructuredOutputParser
|
2 |
| -from langchain.prompts import ChatPromptTemplate |
| 2 | +from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder |
| 3 | +from langchain.schema import HumanMessage |
| 4 | +from langchain.schema.runnable import RunnableLambda |
3 | 5 |
|
4 | 6 | SPAM_INSTRUCTIONS = """
|
5 | 7 | # Role and goal
|
|
120 | 122 | )
|
121 | 123 |
|
122 | 124 |
|
123 |
| -spam_prompt = ChatPromptTemplate( |
| 125 | +spam_prompt_template = ChatPromptTemplate( |
124 | 126 | (
|
125 | 127 | ("system", SPAM_INSTRUCTIONS),
|
126 |
| - ("human", USER_QUESTION), |
| 128 | + MessagesPlaceholder("human_message"), |
127 | 129 | )
|
128 | 130 | ).partial(format_instructions=spam_parser.get_format_instructions())
|
129 | 131 |
|
130 | 132 |
|
131 |
| -topic_prompt = ChatPromptTemplate( |
| 133 | +topic_prompt_template = ChatPromptTemplate( |
132 | 134 | (
|
133 | 135 | ("system", TOPIC_INSTRUCTIONS),
|
134 |
| - ("human", USER_QUESTION), |
| 136 | + ("human_message"), |
135 | 137 | )
|
136 | 138 | ).partial(format_instructions=topic_parser.get_format_instructions())
|
| 139 | + |
| 140 | + |
| 141 | +def create_human_message(inputs: dict) -> dict: |
| 142 | + """ |
| 143 | + Creates the human message, with the image URL's if they're present, and |
| 144 | + then adds it to the inputs dict. Returns the modified inputs dict. |
| 145 | + """ |
| 146 | + content: list[dict] = [ |
| 147 | + { |
| 148 | + "type": "text", |
| 149 | + "text": USER_QUESTION.format(**inputs), |
| 150 | + }, |
| 151 | + ] |
| 152 | + |
| 153 | + for image_url in inputs.get("image_urls", ()): |
| 154 | + content.append( |
| 155 | + { |
| 156 | + "type": "image_url", |
| 157 | + "image_url": { |
| 158 | + "url": image_url, |
| 159 | + }, |
| 160 | + } |
| 161 | + ) |
| 162 | + |
| 163 | + inputs["human_message"] = [HumanMessage(content=content)] |
| 164 | + return inputs |
| 165 | + |
| 166 | + |
| 167 | +spam_prompt = RunnableLambda(create_human_message) | spam_prompt_template |
| 168 | + |
| 169 | + |
| 170 | +topic_prompt = RunnableLambda(create_human_message) | topic_prompt_template |
0 commit comments